<template>
  <div class="app-container">
    <!-- 采购计划 -->
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline filter">
      <div>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="alarmdate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
        <el-form-item label="单据编号">
          <el-input
            v-model="listQuery.fbillno"
            clearable
            class="filter-item"
            style="width: 200px"
            placeholder="请输入单据编号"
          />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
            v-model="listQuery.fbillstate"
            class="filter-item"
            style="width: 200px"
            clearable
            placeholder="请选择单据状态"
          >
            <el-option
              v-for="item in fbillstateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          /> </el-select
        ></el-form-item>
      </div>
      <div>
        <span v-if="this.$store.state.user.fsiteLevel==3" >
          <el-form-item label="客户名称">
            <el-select v-model="listQuery.fsiteNo" disabled clearable filterable class="filter-item" placeholder="请选择客户名称">
              <el-option
                v-for="item in getListfsiteNo"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="计划人员"
          >
            <div style="width: 220px;display:flex;justify-content:flex-end;align-items:center">
              <el-select v-model="listQuery.fplanuser" style="display: inline-block;width:200px" clearable filterable class="filter-item" placeholder="请选择计划人员">
                <el-option
                  v-for="item in getListfplanuser"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <i style="display: inline-block;width:20px;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialoguse('search')"/>
            </div>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="listQuery.fsupno" filterable clearable class="filter-item" placeholder="请选择供应商">
              <el-option
                v-for="item in getListfsupno"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </span>
        <span v-else>
          <el-form-item label="客户名称">
            <el-select v-model="listQuery.fsiteNo" clearable filterable class="filter-item" placeholder="请选择客户名称" @change="changeFsiteNo">
              <el-option
                v-for="item in getListfsiteNo"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="计划人员"
          >
            <div style="width: 220px;display:flex;justify-content:flex-end;align-items:center">
              <el-select v-model="listQuery.fplanuser" style="display: inline-block;width:200px" clearable filterable class="filter-item" placeholder="请选择计划人员">
                <el-option
                  v-for="item in getListfplanuserArea"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <i style="display: inline-block;width:20px;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialoguse('search')"/>
            </div>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="listQuery.fsupno" filterable clearable class="filter-item" placeholder="请选择供应商">
              <el-option
                v-for="item in getListfsupnoArea"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </span>
      </div>
      <el-form-item>
        <!-- v-permission="['purchase:head:read']" -->
        <el-button
          :style="{background:buttonColor.lookup,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"

          @click="handleFilter"
        >查找</el-button
        >
        <el-button
          :style="{background:buttonColor.add,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleCreate"
        >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :header-cell-style="tableColor"
      stripe
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding" >
        <template slot-scope="scope">
          <!-- v-permission="['purchase:head:update']" -->
          <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" >
              编辑
            </div>

            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="audit(scope.row)">
              <img src="../../../public/images/examine.png" >
              确认
            </div>

            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="auditDelete(scope.row)">
              <img src="../../../public/images/del.png" >
              作废
            </div>

            <div :style="{color:buttonColor.edit,cursor:'pointer'}" >
              <img src="../../../public/images/print.png" >
              打印
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        :index="indexMethod"
        align="center"
        label="序"
        type="index"
      />
      <el-table-column width="150" align="center" label="单据编号" prop="fbillno" />
      <el-table-column v-if="this.$store.state.user.fsiteLevel!=3" :formatter="formatfsiteNo" width="200" align="center" label="客户名称" prop="fsiteNo" />
      <el-table-column
        :formatter="datetimeFormat"
        width="100"
        align="center"
        label="计划日期"
        prop="fplandate"
      />
      <el-table-column :formatter="formatfsupno" align="center" label="供应商" prop="fsupno" width="150" />
      <el-table-column :formatter="formatfplanuser" align="center" label="计划人员" prop="fplanuser" />
      <el-table-column align="center" label="品项数" prop="fitemcount" />
      <el-table-column align="center" label="总件数" prop="fpiececount" />
      <el-table-column align="center" label="总价" prop="ftotalamt" />
      <el-table-column align="center" label="备注" prop="fexplanation" />
      <el-table-column align="center" label="单据状态" prop="fbillstate">
        <template slot-scope="scope">
          <span v-if="scope.row.fbillstate === 1" :style="{ color: buttonColor.itemisconfirmed }">{{
            scope.row.fbillstate |
              statusFilter
          }}</span>
          <span v-else-if="scope.row.fbillstate === 2" :style="{ color: buttonColor.itemconfirmed }">{{
            scope.row.fbillstate | statusFilter
          }}</span>
          <span v-else :style="{ color: buttonColor.iteminvalid }">{{ scope.row.fbillstate | statusFilter }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="auto"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="auto"
      >

        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="fbillno">
              <el-input
                :disabled="true"
                v-model="dataForm.fbillno"
            /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item
              label="计划日期"
              prop="fplandate"
            >
              <el-date-picker
                :disabled="true"
                v-model="dataForm.fplandate"
                :picker-options="pickerOptions"
                type="date"
            /> </el-form-item
            >
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="单据状态"
              prop="fbillstate"
            >
              <el-select
                v-model="dataForm.fbillstate"
                disabled
                class="filter-item"
                clearable
              >
                <el-option
                  v-for="item in fbillstateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              v-if="this.$store.state.user.fsiteLevel==3"
              label="客户名称"
              prop="fsiteNo"

            >
              <el-select v-model="dataForm.fsiteNo" disabled clearable filterable class="filter-item" placeholder="请选择客户名称">
                <el-option
                  v-for="item in getListfsiteNo"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item
              v-else
              label="客户名称"
              prop="fsiteNo"
            >
              <el-select v-if="dialogStatus=='create'" v-model="dataForm.fsiteNo" clearable filterable class="filter-item" placeholder="请选择客户名称" @change="changeFsiteNoAdd">
                <el-option
                  v-for="item in getListfsiteNo"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-else v-model="dataForm.fsiteNo" disabled clearable filterable class="filter-item" placeholder="请选择客户名称">
                <el-option
                  v-for="item in getListfsiteNo"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              v-if="this.$store.state.user.fsiteLevel==3"
              label="计划人员"
              prop="fplanuser"
            >
              <div style="display:flex;justify-content:flex-end;align-items:center">
                <el-select v-model="dataForm.fplanuser" style="display: inline-block" clearable filterable class="filter-item" placeholder="请选择计划人员">
                  <el-option
                    v-for="item in getListfplanuser"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
                <i style="display: inline-block;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialoguse('add')"/>
              </div>
            </el-form-item>
            <el-form-item
              v-else
              label="计划人员"
              prop="fplanuser"
            >
              <div style="display:flex;justify-content:flex-end;align-items:center">
                <el-select v-model="dataForm.fplanuser" style="display: inline-block" clearable filterable class="filter-item" placeholder="请选择计划人员">
                  <el-option
                    v-for="item in getListfplanuserAreaAdd"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
                <i style="display: inline-block;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialoguse('add')"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="采购日期"
              prop="forddate"
            >
              <el-date-picker
                v-model="dataForm.forddate"
                type="date"
            /> </el-form-item
            >
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              v-if="this.$store.state.user.fsiteLevel==3"
              label="供应商"
              prop="fsupno"
            >
              <el-select v-if="dialogStatus=='create'" v-model="dataForm.fsupno" filterable clearable class="filter-item" placeholder="请选择供应商">
                <el-option
                  v-for="item in getListfsupno"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-else v-model="dataForm.fsupno" disabled filterable clearable class="filter-item" placeholder="请选择供应商">
                <el-option
                  v-for="item in getListfsupno"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item
              v-else
              label="供应商"
              prop="fsupno"
            >
              <el-select v-if="dialogStatus=='create'" v-model="dataForm.fsupno" filterable clearable class="filter-item" placeholder="请选择供应商">
                <el-option
                  v-for="item in getListfsupnoAreaAdd"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-else v-model="dataForm.fsupno" disabled filterable clearable class="filter-item" placeholder="请选择供应商">
                <el-option
                  v-for="item in getListfsupnoAreaAdd"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item
              label="备注"
              prop="fexplanation"
            >
            <el-input v-model="dataForm.fexplanation" /> </el-form-item
            >
          </el-col>
        </el-row>

      </el-form>
      <el-tabs type="border-card">
        <el-tab-pane label="设备列表">
          <div class="filter-container">
            <el-button
              :style="{background:buttonColor.add,color:buttonColor.color}"
              round
              size="medium"
              class="filter-item"
              icon="el-icon-edit"
              @click="handleUpdate1()"
            >添加</el-button
            ><!-- v-permission="['equipment:eqtDict:create']"-->
            <el-table
              v-loading="listLoading"
              :data="dataForm.plays"
              :header-cell-style="tableColor"
              element-loading-text="正在查询中。。。"
              border
              fit
              highlight-current-row
              height="30vh"
            >
              <el-table-column
                align="center"
                label="序"
                prop="fline"
              />
              <el-table-column
                align="center"
                label="设备编号"
                prop="feuipmentid"
              />
              <el-table-column
                :formatter="fnameFormat"
                align="center"
                label="设备名称"
                prop="fname"
              />
              <el-table-column align="center" label="采购价" prop="fbuyprice" />
              <el-table-column align="center" label="数量" prop="fqty" />
              <el-table-column align="center" label="合计" prop="ftotamt" />
              <el-table-column align="center" label="备注" prop="fmemo" />
              <el-table-column
                align="center"
                width="140"
                label="操作"
                class-name="small-padding"
              >
                <template slot-scope="scope">
                  <el-button
                    :style="{background:buttonColor.delete,color:buttonColor.color}"
                    round
                    size="small"
                    @click="handleDelete1(scope.row)"
                  >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <div v-if="viewFlag==false">
          <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancel()">取消</el-button>
          <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
          <el-button v-else type="primary" @click="updateData">确定</el-button>
        </div>
        <div v-else>
          <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancel()">取消</el-button>
          <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible1"
      width="auto"
      top="5vh"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm1"
        :rules="rules1"
        :model="dataForm1"
        status-icon
        label-position="left"
        label-width="auto"
        style="width: 400px; margin: 0 30px"
      >
        <el-form-item label="行号" prop="fline">
          <el-input v-model="dataForm1.fline" disabled/>
        </el-form-item>
        <el-form-item label="设备编号" prop="feuipmentid">
          <div style="display:flex;align-items:center">
            <el-input v-model="dataForm1.feuipmentid" style="display: inline-block" />
            <i style="display: inline-block;width:20px;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialogEequipmentInfo()"/>
          </div>
        </el-form-item>
        <el-form-item label="设备名称" prop="fname">
          <el-input :disabled="true" v-model="dataForm1.fname" />
        </el-form-item>
        <el-form-item label="采购价" prop="fbuypriceData">
          <el-input v-model="fbuypriceData" />
        </el-form-item>
        <el-form-item label="数量" prop="fqtyData">
          <el-input v-model.number="fqtyData" onkeyup="this.value=this.value.replace(/[^\d]/g,'');" maxlength="6"/>
        </el-form-item>
        <el-form-item label="合计" prop="ftotamtData">
          <el-input :disabled="true" v-model.number="ftotamtData" />
        </el-form-item>
        <el-form-item label="备注" prop="fmemo">
          <el-input v-model="dataForm1.fmemo" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible1 = false">取消</el-button>
        <!-- <el-button  type="warning" @click="addDataContinue">继续添加</el-button> -->
        <el-button type="primary" @click="addData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 设备搜索弹出框 -->
    <equipmentInfoDialog :equipment-info-visible.sync="equipmentInfoVisible" :table-color="tableColor" @equipmentInfoDialog="equipmentInfoDialogValue" />
    <userDialog :search-visibleuse.sync="searchVisibleuse" :fsite-no.sync="userDialogFsiteNo" :table-color="tableColor" @userDialog="userDialogValue" />
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}
.el-button + .el-button {
  margin-left: 1px;
}
</style>

<script>
import { listhead, createhead, updatehead, deletehead } from '@/api/head'
import { fsiteOptionsByLevel, getListArea, getFbillno, checkBiz } from '@/api/area'
import { listinfo } from '@/api/info'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { tableColor, titleColor, buttonColor } from '@/filters/index'
import UserDialog from '@/components/UserDialog'
import EquipmentInfoDialog from '@/components/EquipmentInfoDialog'

const statusMap = {
  1: '待提交',
  2: '已提交',
  8: '已作废'
}

export default {
  name: 'STcOrdplanHead',
  components: { Pagination, UserDialog, EquipmentInfoDialog },
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      buttonColor: buttonColor,
      indexs: 1,
      equipmentInfoVisible: false,
      getListfplanuserAreaAdd: null,
      getListfplanuserArea: null,
      getListfsupnoAreaAdd: null,
      getListfsupnoArea: null,
      viewFlag: false,
      searchVisibleuse: false,
      userDialogFsiteNo: null,
      userFlag: null,

      getListfplanuser: null,
      selectList: [],
      searchListAll: [],
      fbillnoList: null,
      getListfsupno: [],
      getListfsiteNo: null,
      searchVisible: false,
      dataForm1: {
        fline: undefined,
        feuipmentid: undefined,
        fname: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        ftotamt: undefined,
        fmemo: undefined
      },
      fbuypriceData: 0,
      fqtyData: 1,
      ftotamtData: 0,
      dialogFormVisible1: false,
      dialogStatus1: null,
      playsTmp: null,
      actionsTmp: [],
      list: null,
      total: 0,
      listLoading: true,
      alarmdate: null,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: undefined,
        fbillno: undefined,
        fplanuser: undefined,
        ftakedateStart: undefined,
        ftakedateEnd: undefined,
        forddate: undefined,
        fsupno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        fbillno: undefined,
        fsiteNo: undefined,
        fplanuser: undefined,
        fplandate: undefined,
        forddate: undefined,
        fsupno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        id: undefined,
        plays: undefined
      },

      searchList: null,
      listLoadingSearch: true,
      totalSearch: 0,
      listQuerySearch: {
        page: 1,
        limit: 20,
        fequipmentno: undefined,
        sort: 'create_time',
        order: 'desc'
      },

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      rules: {
        fsiteNo: [{ required: true, message: '客户名称不能为空' }],
        fplanuser: [{ required: true, message: '计划人员不能为空', trigger: 'blur' }],
        fplandate: [{ required: true, message: '计划日期不能为空' }],
        forddate: [{ required: true, message: '采购日期不能为空' }],
        fsupno: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
        fitemcount: [
          {
            type: 'number',
            message: '品项数必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        ftotalamt: [],
        fexplanation: [],
        fupddate: [],
        foperator: [],
        fcheckdate: [],
        fcheckuser: []
      },
      rules1: {
        feuipmentid: [
          { required: true, message: '设备编号不能为空' },
          {
            type: 'number',
            message: '设备编号必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fline: [
          { required: true, message: '行号不能为空' },
          { type: 'number', message: '行号必须为数字值', transform: (value) => Number(value) }
        ],
        fname: [{ required: true, message: '设备名称不能为空' }],
        fbuyprice: [{ required: true, message: '采购价不能为空' }],
        fqty: [
          { required: true, message: '数量不能为空' },
          {
            type: 'number',
            message: '数量必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        ftotamt: [{ required: true, message: '合计不能为空' }],
        fmemo: []
      },
      fbillstateOptions: [
        { value: 1, label: '待提交' },
        { value: 2, label: '已提交' },
        { value: 8, label: '已作废' }
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },

  watch: {
    fbuypriceData: function(val) {
      if (this.fqtyData && val) {
        const num = (this.fqtyData * parseFloat(val)).toFixed(2)
        return this.ftotamtData = num
      } else {
        return this.ftotamtData = 0
      }
    },

    fqtyData: function(val) {
      if (this.fqtyData && val) {
        const num = (parseFloat(this.fbuypriceData) * val).toFixed(2)
        return this.ftotamtData = num
      } else {
        return this.ftotamtData = 0
      }
    }

  },
  created() {
    if (this.$store.state.user.fsiteLevel == 3) {
      this.listQuery.fsiteNo = this.$store.state.user.fsiteNo
      // 供应商
      getListArea({ flag: 6, arg1: this.$store.state.user.fsiteNo })
        .then(response => {
          this.getListfsupno = response.data.data.list
        })
        .catch(() => {
          this.getListfsupno = []
        })

        // 人员弹出框
      getListArea({ flag: 13, arg1: this.$store.state.user.fsiteNo })
        .then(response => {
          this.getListfplanuser = response.data.data.list
        })
        .catch(() => {
          this.getListfplanuser = []
        })
    } else {
      // 供应商
      getListArea({ flag: 6 })
        .then(response => {
          this.getListfsupno = response.data.data.list
        })
        .catch(() => {
          this.getListfsupno = []
        })

        // 人员弹出框
      getListArea({ flag: 13 })
        .then(response => {
          this.getListfplanuser = response.data.data.list
        })
        .catch(() => {
          this.getListfplanuser = []
        })
    }
    this.alarmdate = [this.parserDate(moment(new Date().setDate(1)).format('YYYY-MM-DD')), new Date()]
    this.getList()
    fsiteOptionsByLevel(3)
      .then(response => {
        this.getListfsiteNo = response.data.data.list
      })
      .catch(() => {
        this.getListfsiteNo = []
      })

      // 全部设备列表
    listinfo()
      .then(response => {
        this.searchListAll = response.data.data.list
      })
      .catch(() => {
        this.searchListAll = []
      })
  },
  methods: {
    parserDate(date) {
      var t = Date.parse(date)
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, '/')))
      }
    },
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
    formatfsiteNo: function(row, column) {
      if (this.getListfsiteNo) {
        for (let i = 0; i < this.getListfsiteNo.length; i++) {
          if (row.fsiteNo === this.getListfsiteNo[i].value) {
            return this.getListfsiteNo[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },

    changeFsiteNo(data) {
      this.listQuery.fsupno = ''
      this.listQuery.fplanuser = ''
      this.getListfsupnoArea = []
      this.getListfplanuserArea = []
      if (data) {
        // 供应商
        getListArea({ flag: 6, arg1: data })
          .then(response => {
            this.getListfsupnoArea = response.data.data.list
          })
          .catch(() => {
            this.getListfsupnoArea = []
          })

          // 人员弹出框
        getListArea({ flag: 13, arg1: data })
          .then(response => {
            this.getListfplanuserArea = response.data.data.list
          })
          .catch(() => {
            this.getListfplanuserArea = []
          })
      }
    },

    changeFsiteNoAdd(data) {
      this.dataForm.fsupno = ''
      this.dataForm.fplanuser = ''
      this.getListfsupnoAreaAdd = []
      this.getListfplanuserAreaAdd = []
      if (data) {
        // 供应商
        getListArea({ flag: 6, arg1: data })
          .then(response => {
            this.getListfsupnoAreaAdd = response.data.data.list
          })
          .catch(() => {
            this.getListfsupnoAreaAdd = []
          })

        // 人员弹出框
        getListArea({ flag: 13, arg1: data })
          .then(response => {
            this.getListfplanuserAreaAdd = response.data.data.list
          })
          .catch(() => {
            this.getListfplanuserAreaAdd = []
          })
      }
    },

    // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value
      if (value === 'add') {
        this.userDialogFsiteNo = this.dataForm.fsiteNo
      } else {
        this.userDialogFsiteNo = this.listQuery.fsiteNo
      }
      this.searchVisibleuse = true
    },

    // 人员弹出框返回值
    userDialogValue(value) {
      if (this.userFlag === 'add') {
        this.dataForm.fplanuser = value.user.id.toString()
      } else {
        this.listQuery.fplanuser = value.user.id.toString()
      }
    },

    // 计划人员 getListfplanuser
    formatfplanuser: function(row, column) {
      if (this.getListfplanuser) {
        for (let i = 0; i < this.getListfplanuser.length; i++) {
          if (row.fplanuser == this.getListfplanuser[i].value) {
            return this.getListfplanuser[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },

    // 供应商
    formatfsupno: function(row, column) {
      if (this.getListfsupno.length > 0) {
        for (let i = 0; i < this.getListfsupno.length; i++) {
          if (row.fsupno === this.getListfsupno[i].value) {
            return this.getListfsupno[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 设备名称
    fnameFormat: function(row, column) {
      if (this.searchListAll.length > 0) {
        for (let i = 0; i < this.searchListAll.length; i++) {
          if (row.feuipmentid == this.searchListAll[i].feuipmentid) {
            return this.searchListAll[i].fequipmentname
          }
        }
        return ''
      } else {
        return ''
      }
    },

    // 设备信息弹出框
    searchDialogEequipmentInfo() {
      this.equipmentInfoVisible = true
    },

    // 设备信息弹出框
    equipmentInfoDialogValue(value) {
      this.dataForm1.feuipmentid = value.info.feuipmentid
      this.dataForm1.fname = value.info.fequipmentname
    },

    formatDate: function(date) {
      if (typeof (date) === 'object') {
        var ym
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        ym = '' + y + m + d
        return ym
      } else {
        return date
      }
    },

    getList() {
      this.listQuery.ftakedateStart = this.alarmdate == null ? null : this.formatDate(this.alarmdate[0])
      this.listQuery.ftakedateEnd = this.alarmdate == null ? null : this.formatDate(this.alarmdate[1])

      this.listLoading = true
      listhead(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleDelete1(row) {
      const index = this.dataForm.plays.indexOf(row)
      this.dataForm.plays.splice(index, 1)
      this.selectList.splice(index, 1)
      // this.dataForm.plays.pop(row)
    },
    handleUpdate1() {
      this.dialogStatus1 = 'update'
      this.dialogFormVisible1 = true
      // this.multipleSelection = []
      this.dataForm1 = {
        fline: this.indexs,
        feuipmentid: undefined,
        fname: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        ftotamt: undefined,
        fmemo: undefined
      }
      this.fbuypriceData = 0,
      this.fqtyData = 1,
      this.ftotamtData = 0,
      this.$nextTick(() => {
        this.$refs['dataForm1'].clearValidate()
      })
    },
    cancel() {
      this.indexs = 1
      this.dialogFormVisible = false
      this.selectList = []
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.actionsTmp
          this.dataForm.plays = this.playsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    },
    // 弹窗点击关闭前的回调
    handleClose() {
      this.indexs = 1
      this.dialogFormVisible = false
      this.selectList = []
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.actionsTmp
          this.dataForm.plays = this.playsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    },
    addData() {
      this.$refs['dataForm1'].validate((valid) => {
        this.dataForm1.fbuyprice = parseFloat(this.fbuypriceData)
        this.dataForm1.fqty = this.fqtyData
        this.dataForm1.fline = this.indexs
        this.dataForm1.ftotamt = parseFloat(this.ftotamtData)
        // 判断设备是否重复
        const tem = this.selectList.indexOf(Number(this.dataForm1.feuipmentid))
        if (tem < 0) {
          if (valid) {
            this.dialogFormVisible1 = false
            this.dataForm.plays.push(this.dataForm1)
            this.selectList.push(Number(this.dataForm1.feuipmentid))
            this.indexs++
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '所选设备重复'
          })
          return
        }
      })
    },
    addDataContinue() {
      this.$refs['dataForm1'].validate((valid) => {
        this.dataForm1.fbuyprice = parseFloat(this.fbuypriceData)
        this.dataForm1.fqty = this.fqtyData
        this.dataForm1.ftotamt = parseFloat(this.ftotamtData)
        // 判断设备是否重复
        const tem = this.selectList.indexOf(Number(this.dataForm1.feuipmentid))
        if (tem < 0) {
          if (valid) {
            this.dataForm.plays.push(this.dataForm1)
            this.selectList.push(Number(this.dataForm1.feuipmentid))
            this.$nextTick(() => {
              this.$refs['dataForm1'].clearValidate()
            })
            this.dataForm1 = {
              fline: undefined,
              feuipmentid: undefined,
              fname: undefined,
              fbuyprice: undefined,
              fqty: undefined,
              ftotamt: undefined,
              fmemo: undefined
            }
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '所选设备重复'
          })
          return
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fbillno: undefined,
        fsiteNo: undefined,
        fplanuser: undefined,
        fplandate: undefined,
        forddate: undefined,
        fsupno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        id: undefined,
        plays: []
      }
    },
    handleCreate() {
      this.resetForm()

      // 单据编号
      getFbillno({ flag: 2005 })
        .then((response) => {
          if (response) {
            this.dataForm.fbillno = response.data.data
            this.dialogFormVisible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
          }
        })
        .catch(() => {
          this.dataForm.fbillno = ''
        })

      this.dialogStatus = 'create'
      if (this.$store.state.user.fsiteLevel == 3) {
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo
        this.dataForm.fplanuser = this.$store.state.user.id.toString()
        if (this.getListfsupno.length > 0) {
          this.dataForm.fsupno = this.getListfsupno[0].value
        }
      } else {
        this.getListfsupnoAreaAdd = []
        this.getListfplanuserAreaAdd = []
      }
      this.dataForm.fplandate = new Date()
      this.dataForm.forddate = new Date()
      this.dataForm.fbillstate = 1
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        this.dataForm1.fline = this.indexs
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          createhead(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加采购计划主表成功'
              })
              this.indexs++
              this.selectList = []
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleUpdate(row) {
      if (row.fbillstate == '1') {
        this.viewFlag = false
      } else {
        this.viewFlag = true
      }

      if (this.$store.state.user.fsiteLevel != 3) {
        // 供应商
        getListArea({ flag: 6, arg1: row.fsiteNo })
          .then(response => {
            this.getListfsupnoAreaAdd = response.data.data.list
          })
          .catch(() => {
            this.getListfsupnoAreaAdd = []
          })

        // 人员弹出框
        getListArea({ flag: 13, arg1: row.fsiteNo })
          .then(response => {
            this.getListfplanuserAreaAdd = response.data.data.list
          })
          .catch(() => {
            this.getListfplanuserAreaAdd = []
          })
      }

      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.actionsTmp = row
      this.playsTmp = []
      if (row.plays) {
        row.plays.forEach((v) => {
          this.playsTmp.push(v)
          this.selectList.push(v.feuipmentid)
        })
      }
      var end = row.plays[row.plays.length - 1]
      this.indexs = end.fline + 1
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          updatehead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新采购计划主表成功'
              })
              this.selectList = []
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },

    auditDelete(row) {
      this.$confirm('是否确定作废', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
        this.dataForm.fbillstate = 8
        updatehead(this.dataForm, this.$route.query.id)
          .then(() => {
            for (const v of this.list) {
              if (v.fbillno === this.dataForm.fbillno) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.$notify.success({
              title: '成功',
              message: '作废成功'
            })
            this.selectList = []
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    audit(row) {
      this.$confirm('是否确定', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
        checkBiz({ pBillNo: this.dataForm.fbillno, pBillState: 2, pBizType: 's_tc_ordplan_head', pUser: this.$store.state.user.id })
          .then(() => {
            for (const v of this.list) {
              if (v.fbillno === this.dataForm.fbillno) {
                this.dataForm.fbillstate = 2
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.$notify.success({
              title: '成功',
              message: '确认成功'
            })
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除采购计划主表', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletehead(row)
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '删除采购计划主表成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
